
package com.jf.cloud.service.sysmanager.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jf.cloud.service.sysmanager.common.base.BaseService;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.jdbc.RowMapperFactory;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.constant.Constant;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.TradeType;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgFinanceFlowDetailService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserMatchService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserTeamService;
import com.jf.cloud.service.sysmanager.entity.PubgFinanceFlowDetail;
import com.jf.cloud.service.sysmanager.entity.PubgMatch;
import com.jf.cloud.service.sysmanager.entity.PubgTeam;
import com.jf.cloud.service.sysmanager.entity.PubgUser;
import com.jf.cloud.service.sysmanager.entity.PubgUserClub;
import com.jf.cloud.service.sysmanager.entity.PubgUserLoginBanding;
import com.jf.cloud.service.sysmanager.entity.PubgUserMatch;
import com.jf.cloud.service.sysmanager.entity.PubgUserTeam;


/**
 * 员工服务实现
 * 
 * @author 绝峰代码机1.0 创建时间：2018-03-31
 */
@Service("pubgUserService")
public class PubgUserServiceImpl extends BaseService<PubgUser, Long> implements IPubgUserService {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PubgUserServiceImpl.class);

	/**
	 * JPA公共DAO
	 */
	@Resource
	private BaseDao baseDao;
	
	@Resource
	private IPubgUserClubService pubgUserClubService;
	
	@Resource
	private IPubgUserTeamService pubgUserTeamService;
	
	@Resource
	private IPubgUserMatchService pubgUserMatchService;
	
	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;
	
	/**
	 * 获取用户信息（后台调用）
	 * 
	 * @author 朱建文 创建时间：2018年4月9日 上午11:19:31
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getUserInfoDetail(Long rowId) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		
		// 查询用户信息
		sql.append(" SELECT ");
		sql.append("   USER_ACCOUNT userAccount, NICKNAME nickname, LINK_QQ linkQq, GAME_ROLE gameRole, USER_ROLE userRole, ");
		sql.append("   BALANCE balance, MATCH_AMOUNT matchAmount, WIN_AMOUNT winAmount, WIN_SUM winSum ");
		sql.append(" FROM pubg_user ");
		sql.append(" WHERE ROW_ID = ?");
		Map<String, Object> userMap = this.baseDao.findMap(sql.toString(), rowId);
		dataMap.put("userData", userMap);
		
		sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append("   CLUB_ID clubId, TEAM_ID teamId, TEAM_NAME teamName, USER_TEAM_BALANCE userTeamBalance,");
		sql.append("   RECHARGE_SUM rechangeSum, MATCH_AMOUNT matchAmount, WIN_AMOUNT winAmount, WIN_SUM winSum ");
		sql.append(" FROM pubg_user_team ");
		sql.append(" WHERE USER_ID = ? ");
		List<Map<String, Object>> teamDetailList = this.baseDao.findMapList(sql.toString(), rowId);
		if (teamDetailList == null || teamDetailList.isEmpty()) {
			return dataMap;
		}
		
		// 队员加入的战队详细数据
		String club = "", team = "";
		boolean isExistTeamId = false;
		List<Map<String, Object>> teamList = new ArrayList<Map<String,Object>>();
		Map<String, Object> tempMap = null;
		for (Map<String, Object> map : teamDetailList) {
			isExistTeamId = false;
			
			// 战队的key   
			team = "club" + map.get("clubId") + "team" + map.get("teamId");
			dataMap.put(team, map);
			club = "club" + map.get("clubId") + "team";
			
			
			if (dataMap.containsKey(club)) {
				teamList = (List<Map<String, Object>>) dataMap.get(club);
			} else {
				teamList = new ArrayList<Map<String,Object>>();
			}
			
			for (Map<String, Object> teamMap : teamList) {
				if (map.get("teamId").equals(teamMap.get("teamId"))) {
					isExistTeamId = true;
					break;
				}
			}
			
			// 放入战队详情
			if (!isExistTeamId) {
				tempMap = new HashMap<String, Object>();
				tempMap.put("teamId", map.get("teamId"));
				tempMap.put("teamName", map.get("teamName"));
				teamList.add(tempMap);
			}
			dataMap.put(club, teamList);
		}
		
		// 队员加入的俱乐部
		sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append("   CLUB_ID clubId, CLUB_NAME clubName, USER_CLUB_BALANCE userClubBalance, ");
		sql.append("   RECHARGE_SUM rechangeSum, MATCH_AMOUNT matchAmount, WIN_AMOUNT winAmount, WIN_SUM winSum ");
		sql.append(" FROM pubg_user_club ");
		sql.append(" WHERE USER_ID = ? ");
		List<Map<String, Object>> dataList = this.baseDao.findMapList(sql.toString(), rowId);
		dataMap.put("clubData", dataList);
		return dataMap;
	}

	/**
	 * 获取用户信息（前台调用）
	 * 
	 * @author 朱建文 创建时间：2018年4月9日 上午11:19:31
	 */
	public Map<String, Object> getUserInfo(Long rowId) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append("   ROW_ID rowId, USER_ACCOUNT userAccount, IFNULL(NICKNAME, '') nickname, ");
		sql.append("   IFNULL(NICKNAME_INITIAL, '') nicknameInitial, IFNULL(LINK_QQ, '') linkQq, ");
		sql.append("   IFNULL(GAME_ROLE, '') gameRole, IFNULL(PHOTO, '') photo, IFNULL(USER_ROLE, '') userRole, ");
		sql.append("   IFNULL(BALANCE, 0) balance, IFNULL(INFO_COMPLETE_FLAG, 0) infoCompleteFlag, IFNULL(REAL_NAME_FLAG, 0) realNameFlag ");
		sql.append(" FROM ");
		sql.append("   pubg_user ");
		sql.append(" WHERE ");
		sql.append("   ROW_ID = ? ");
		return baseDao.findMap(sql.toString(), rowId);
	}
	
	/**
	 * 更新用户信息
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 下午1:32:25
	 */
	@Transactional
	public boolean updateUserInfo(PubgUser pubgUser) {
		boolean successFlag = false;
		try {
			String sql = "UPDATE pubg_user SET NICKNAME = ?, NICKNAME_INITIAL = ?, GAME_ROLE = ?, LINK_QQ = ?, INFO_COMPLETE_FLAG = ? WHERE ROW_ID = ?";
			successFlag = this.baseDao.safeUpdate(sql, 1, pubgUser.getNickname(), pubgUser.getNicknameInitial(), 
					pubgUser.getGameRole(), pubgUser.getLinkQq(), pubgUser.getInfoCompleteFlag(), pubgUser.getRowId());
		} catch (DataAccessException e) {
			log.error("更新用户信息出错！", e);
		}
		return successFlag;
	}
	
	/**
	 * 申请加入战队插入 队员-战队，俱乐部关系
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午7:56:37
	 */
	@Transactional
	public boolean applyJoinTeam(PubgUserTeam pubgUserTeam, PubgTeam pubgTeam) {
		boolean isSuccess = false;
		try {
			
			// 插入队员-战队关系
			pubgUserTeam.setApplyTime(DateUtil.getCurrentDateTime());
			pubgUserTeam.setClubId(pubgTeam.getClubId());
			pubgUserTeam.setClubName(pubgTeam.getClubName());
			pubgUserTeam.setTeamId(pubgTeam.getRowId());
			pubgUserTeam.setTeamName(pubgTeam.getTeamName());
			pubgUserTeam.setRelationState(PubgConstant.USER_CLUB_RELATION_STATE_1);
			pubgUserTeam.setMatchAmount(0);
			pubgUserTeam.setRechargeSum(0.0);
			pubgUserTeam.setUserTeamBalance(0.0);
			pubgUserTeam.setWinAmount(0);
			pubgUserTeam.setWinSum(0.0);
			this.pubgUserTeamService.saveObj(pubgUserTeam);
			
			// 插入队员-俱乐部关系
			String sql = "SELECT COUNT(0) FROM pubg_user_club WHERE CLUB_ID = ? AND USER_ID = ?";
			if (this.baseDao.find(sql, Integer.class, pubgUserTeam.getClubId(), pubgUserTeam.getUserId()) <= 0) {
				PubgUserClub pubgUserClub = new PubgUserClub();
				pubgUserClub.setApplyTime(DateUtil.getCurrentDateTime());
				pubgUserClub.setClubId(pubgTeam.getClubId());
				pubgUserClub.setClubName(pubgTeam.getClubName());
				pubgUserClub.setUserId(pubgUserTeam.getUserId());
				pubgUserClub.setUserAccount(pubgUserTeam.getUserAccount());
				pubgUserClub.setInviteFrom(pubgUserTeam.getInviteFrom());
				pubgUserClub.setRelationState(PubgConstant.USER_CLUB_RELATION_STATE_1);
				pubgUserClub.setMatchAmount(0);
				pubgUserClub.setRechargeSum(0.0);
				pubgUserClub.setUserClubBalance(0.0);
				pubgUserClub.setWinAmount(0);
				pubgUserClub.setWinSum(0.0);
				this.pubgUserClubService.saveObj(pubgUserClub);
			}
			isSuccess = true;
		} catch (Exception e) {
			log.error("申请加入战队插入 队员-战队，俱乐部关系出错！", e);
			throw new RuntimeException("申请加入战队插入 队员-战队，俱乐部关系出错！", e);
		}
		return isSuccess;
	}
	
	/**
	 * 获取战队下的队员列表
	 * @param isGroup 是否需要按字母简拼分组
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 下午7:50:47
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> findMemberList(OPaging<Map<String, Object>> page, Integer userRole, boolean isGroup) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
		try {
			StringBuffer sb = new StringBuffer(255);
			String whereSql = "";
			
			// 查询 战队ID 或者 俱乐部ID
			String sql = "";
			Long rowId = 0L;
			if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
				sql = "SELECT ROW_ID FROM pubg_team WHERE CAPTAIN_ID LIKE '%" + page.getWm().get("non_userId") + ",%'";
				rowId = this.baseDao.find(sql, Long.class);
				page.getWm().put("a.TEAM_ID", rowId);
			} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
				sql = "SELECT ROW_ID FROM pubg_club WHERE MINISTER_ID LIKE '%" + page.getWm().get("non_userId") + ",%'";
				rowId = this.baseDao.find(sql, Long.class);
				page.getWm().put("a.CLUB_ID", rowId);
			}
			
			// 队员名称/昵称 筛选
			String str = page.getWm().get("non_value") + "";
			if (str != null && str.length() > 0 && !"null".equals(str)) {
				whereSql += " WHERE (b.USER_ACCOUNT LIKE '%" + str + "%' OR b.NICKNAME LIKE '%" + str + "%') ";
			}
			if (whereSql.length() <= 0) {
				whereSql = page.getWhereSQL(true);
			} else {
				whereSql += " AND " + page.getWhereSQL();
			}

			// 查询未审核/已审核人数
			if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
				sql = "SELECT COUNT(IF(RELATION_STATE = 1, 0, NULL)) notAudit, COUNT(IF(RELATION_STATE = 2, 0, NULL)) audited ";
				sql += " FROM pubg_user_team WHERE TEAM_ID = ? ";
			} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
				sql = "SELECT COUNT(IF(RELATION_STATE = 1, 0, NULL)) notAudit, COUNT(IF(RELATION_STATE = 2, 0, NULL)) audited ";
				sql += " FROM pubg_user_club WHERE CLUB_ID = ? ";
			} 
			Map<String, Object> numMap = this.baseDao.findMap(sql, rowId);
			dataMap.putAll(numMap);
			
			// 查询队员的参赛率
			StringBuffer joinMatchRatioSql = new StringBuffer();
			joinMatchRatioSql.append(" SELECT ");
			joinMatchRatioSql.append("   b.CLUB_ID, b.CLUB_NAME, b.TEAM_ID, b.TEAM_NAME, b.USER_ID, b.USER_ACCOUNT, ");
			joinMatchRatioSql.append("   b.joinMatch, COUNT(a.CLUB_ID), FORMAT(joinMatch/COUNT(a.CLUB_ID) * 100, 2) jmRatio ");
			joinMatchRatioSql.append(" FROM ");
			joinMatchRatioSql.append("   pubg_match a, ");
			joinMatchRatioSql.append("   ( ");
			joinMatchRatioSql.append("    SELECT ");
			joinMatchRatioSql.append("      CLUB_ID, CLUB_NAME, TEAM_ID, TEAM_NAME, ");
			joinMatchRatioSql.append("      USER_ID, USER_ACCOUNT, COUNT(0) joinMatch ");
			joinMatchRatioSql.append("    FROM ");
			joinMatchRatioSql.append("      pubg_user_match ");
			joinMatchRatioSql.append("    WHERE ");
			if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
				joinMatchRatioSql.append(" TEAM_ID = ? ");
			} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
				joinMatchRatioSql.append(" CLUB_ID = ? ");
			}
			joinMatchRatioSql.append("     GROUP BY USER_ID ");
			joinMatchRatioSql.append("   ) b ");
			joinMatchRatioSql.append(" WHERE ");
			joinMatchRatioSql.append("   a.MATCH_STATE = '70' AND a.CLUB_ID = b.CLUB_ID ");
			if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
				joinMatchRatioSql.append(" AND a.MATCH_TEAM_ID LIKE '%" + rowId + ",%' ");
			}
			joinMatchRatioSql.append("   GROUP BY USER_ID ");
			List<Map<String, Object>> jmRatioList = this.baseDao.findMapList(joinMatchRatioSql.toString(), rowId);
			Map<String, Object> jmRatioMap = new HashMap<String, Object>();
			for (Map<String, Object> map : jmRatioList) {
				jmRatioMap.put(map.get("USER_ID").toString(), map.get("jmRatio") + "%");
			}
			
			// 按 昵称 首字母分组
			if (isGroup) {
				
				// 获取 昵称简拼列表
				if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
					sb.append(" SELECT NICKNAME_INITIAL ");
					sb.append(" FROM pubg_user_team a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
				} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
					sb.append(" SELECT NICKNAME_INITIAL ");
					sb.append(" FROM pubg_user_club a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
				}
				sb.append(whereSql);
				if (whereSql.indexOf("WHERE") >= 0) {
					sb.append(" AND b.NICKNAME_INITIAL IS NOT NULL ");
				} else {
					sb.append(" WHERE b.NICKNAME_INITIAL IS NOT NULL ");
				}
				sb.append(" GROUP BY b.NICKNAME_INITIAL ORDER BY b.NICKNAME_INITIAL ");
				List<String> initialList = this.baseDao.findList(sb.toString(), String.class, page.getParamList().toArray());
				
				// 查询数据的sql
				sb = new StringBuffer(255);
				if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
					sb.append(" SELECT ");
					sb.append("   IFNULL(b.PHOTO, '') photo, IFNULL(b.NICKNAME, '') nickname, IFNULL(b.GAME_ROLE, '') gameRole, ");
					sb.append("   IFNULL(a.USER_TEAM_BALANCE, 0) balance, a.RELATION_STATE state, b.ROW_ID rowId ");
					sb.append(" FROM ");
					sb.append("   pubg_user_team a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
				} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
					sb.append(" SELECT ");
					sb.append("   IFNULL(b.PHOTO, '') photo, IFNULL(b.NICKNAME, '') nickname, IFNULL(b.GAME_ROLE, '') gameRole, ");
					sb.append("   IFNULL(a.USER_CLUB_BALANCE, 0) balance, b.ROW_ID rowId ");
					sb.append(" FROM ");
					sb.append("   pubg_user_club a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
				}
				
				// where条件
				if (whereSql.length() <= 0) {
					whereSql = " WHERE ";
				} else {
					whereSql += " AND ";
				}
				sb.append(whereSql);
				
				// 遍历简拼 分别查询
				String sqlTemp = "";
				Map<String, Object> tempMap = null;
				List<Map<String, Object>> initialData = new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> tempData = new ArrayList<Map<String, Object>>();
				for (String initial : initialList) {
					tempMap = new HashMap<String, Object>();
					
					if (initial == null) {
						sqlTemp = sb.toString() + " b.NICKNAME_INITIAL IS NULL ";
					} else {
						sqlTemp = sb.toString() + " b.NICKNAME_INITIAL = '" + initial + "'";
					}
					initialData = this.baseDao.findMapList(sqlTemp, page.getParamList().toArray());
					
					// 不是A-Z的 统一放到“其他”中
					if (Constant.CAPITAL_LETTER.indexOf(initial) < 0) {
						initial = "";
						Iterator<Map<String, Object>> it = tempList.iterator();  
						while(it.hasNext()){
							Map<String, Object> map = it.next();
							if (initial.equals(map.get("keys"))) {
								tempData = (List<Map<String, Object>>) map.get("values");
								it.remove();
								break;
							}  
						}  
						
						if (tempData != null && !tempData.isEmpty()) {
							initialData.addAll(tempData);
						}
					}
					tempMap.put("keys", initial);
					tempMap.put("values", initialData);
					tempList.add(tempMap);
				}
				dataMap.put("data", tempList);

				// 查询到数据时，并且查询的不是“未审核”，返回参赛率
				if (tempList != null && !tempList.isEmpty() && !"1".equals(page.getWm().get("a.RELATION_STATE"))) {
					dataMap.put("jmRatio", jmRatioMap);
				}
				return dataMap;
			}
			
			// 不需要 按昵称首字母 分组
			sb = new StringBuffer(255);
			if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
				sb.append(" SELECT ");
				sb.append("   IFNULL(b.PHOTO, '') photo, IFNULL(b.NICKNAME, '') nickname, IFNULL(b.GAME_ROLE, '') gameRole, ");
				sb.append("   IFNULL(a.USER_TEAM_BALANCE, 0) balance, a.RELATION_STATE state, b.ROW_ID rowId ");
				sb.append(" FROM ");
				sb.append("   pubg_user_team a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
			} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
				sb.append(" SELECT ");
				sb.append("   IFNULL(b.PHOTO, '') photo, IFNULL(b.NICKNAME, '') nickname, IFNULL(b.GAME_ROLE, '') gameRole, ");
				sb.append("   IFNULL(a.USER_CLUB_BALANCE, 0) balance, b.ROW_ID rowId ");
				sb.append(" FROM ");
				sb.append("   pubg_user_club a LEFT JOIN pubg_user b ON a.USER_ID = b.ROW_ID ");
			}
			sb.append(whereSql);
			if (whereSql.indexOf("WHERE") >= 0) {
				sb.append(" AND b.NICKNAME_INITIAL IS NOT NULL ");
			} else {
				sb.append(" WHERE b.NICKNAME_INITIAL IS NOT NULL ");
			}
			
			// 不需要分页 180410
			tempList = this.baseDao.findMapList(sb.toString(), page.getParamList().toArray());
			dataMap.put("data", tempList);
			
			// 查询到数据时，并且查询的不是“未审核”，返回参赛率
			if (tempList != null && !tempList.isEmpty() && !"1".equals(page.getWm().get("a.RELATION_STATE"))) {
				dataMap.put("jmRatio", jmRatioMap);
			}
		} catch (Exception e) {
			log.error("获取战队下的队员列表出错！", e);
		}
		return dataMap;
	}
	
	/**
	 * 队员申请加入比赛
	 * 
	 * @author 朱建文 创建时间：2018年4月8日 上午10:54:16
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
	public void applyJoinMatch(PubgUserTeam pubgUserTeam, PubgMatch pubgMatch, Double userBalance) throws Exception {
		StringBuffer sb = new StringBuffer(255);
		try {
			
			// 先扣款   用户-俱乐部
			sb.append(" UPDATE ");
			sb.append("   pubg_user_club ");
			sb.append(" SET ");
			sb.append("   USER_CLUB_BALANCE = USER_CLUB_BALANCE - ? ");
			sb.append(" WHERE ");
			sb.append("   USER_ID = ? AND CLUB_ID = ? ");
			this.baseDao.safeUpdate(sb.toString(), 0, pubgMatch.getApplyFee(), 
					pubgUserTeam.getUserId(), pubgUserTeam.getClubId());
			
			// 先扣款  用户-战队
			sb = new StringBuffer(255);
			sb.append(" UPDATE ");
			sb.append("   pubg_user_team ");
			sb.append(" SET ");
			sb.append("   USER_TEAM_BALANCE = USER_TEAM_BALANCE - ? ");
			sb.append(" WHERE ");
			sb.append("   USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? AND USER_TEAM_BALANCE = ? ");
			this.baseDao.safeUpdate(sb.toString(), 1, pubgMatch.getApplyFee(), 
					pubgUserTeam.getUserId(), pubgUserTeam.getTeamId(), 
					pubgUserTeam.getClubId(), pubgUserTeam.getUserTeamBalance());
			
			// 用户总余额 减
			sb = new StringBuffer(255);
			sb.append(" UPDATE ");
			sb.append("   pubg_user ");
			sb.append(" SET ");
			sb.append("   BALANCE = BALANCE - ? ");
			sb.append(" WHERE ");
			sb.append("   ROW_ID = ? AND USER_ROLE = ? AND BALANCE = ? ");
			this.baseDao.safeUpdate(sb.toString(), 1, pubgMatch.getApplyFee(), 
					pubgUserTeam.getUserId(), UserConstant.USER_ROLE_10.getId(), userBalance);

			// 更新比赛的报名人数、报名金额
			sb = new StringBuffer(255);
			sb.append(" UPDATE ");
			sb.append("   pubg_match ");
			sb.append(" SET ");
			sb.append("   APPLY_PEOPLE_NUM = APPLY_PEOPLE_NUM + 1, APPLY_SUM_FINAL = APPLY_SUM_FINAL + ? ");
			sb.append(" WHERE ");
			sb.append("   ROW_ID = ? AND CLUB_ID = ? AND APPLY_PEOPLE_NUM = ? AND APPLY_SUM_FINAL = ? ");
			this.baseDao.safeUpdate(sb.toString(), 1, pubgMatch.getApplyFee(), pubgMatch.getRowId(), 
					pubgUserTeam.getClubId(), pubgMatch.getApplyPeopleNum(), pubgMatch.getApplySumFinal());
			
			// 财务流水
			PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
			pubgFinanceFlowDetail.setClubId(pubgMatch.getClubId());
			pubgFinanceFlowDetail.setClubName(pubgMatch.getClubName());
			pubgFinanceFlowDetail.setTeamId(pubgUserTeam.getTeamId());
			pubgFinanceFlowDetail.setTeamName(pubgUserTeam.getTeamName());
			pubgFinanceFlowDetail.setUserId(pubgUserTeam.getUserId());
			pubgFinanceFlowDetail.setUserAccount(pubgUserTeam.getUserAccount());
			pubgFinanceFlowDetail.setInOutFlag(2);
			pubgFinanceFlowDetail.setTradeMoney(pubgMatch.getApplyFee());
			pubgFinanceFlowDetail.setTradeMoneyAfter(pubgUserTeam.getUserTeamBalance() - pubgMatch.getApplyFee());
			pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_APPLY_REDUCE.key());
			pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_APPLY_REDUCE.value());
			pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
			pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
			this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
			
			// 插入报名记录
			PubgUserMatch pubgUserMatch = new PubgUserMatch();
			pubgUserMatch.setMatchId(pubgMatch.getRowId());
			pubgUserMatch.setMatchName(pubgMatch.getMatchName());
			pubgUserMatch.setClubId(pubgMatch.getClubId());
			pubgUserMatch.setClubName(pubgMatch.getClubName());
			pubgUserMatch.setTeamId(pubgUserTeam.getTeamId());
			pubgUserMatch.setTeamName(pubgUserTeam.getTeamName());
			pubgUserMatch.setUserId(pubgUserTeam.getUserId());
			pubgUserMatch.setUserAccount(pubgUserTeam.getUserAccount());
			pubgUserMatch.setUserState(UserMatchConstant.USER_MATCH_10.getId() + "");
			pubgUserMatch.setApplyFee(pubgMatch.getApplyFee());
			pubgUserMatch.setApplyTime(DateUtil.getCurrentDateTime());
			pubgUserMatch.setInviteFrom(pubgUserTeam.getInviteFrom());
			this.pubgUserMatchService.saveObj(pubgUserMatch);
		} catch (Exception e) {
			throw new RuntimeException("队员申请加入比赛出错！", e);
		}
	}
	
	/**
	 * 更新邀请码
	 * 
	 * @author 朱建文 创建时间：2018年4月9日 下午7:02:30
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
	public void updateInvideCode(PubgUser pubgUser, Long rowId, String inviteCode) throws Exception {
		StringBuffer sb = new StringBuffer(255);
		try {
			if (UserConstant.USER_ROLE_20.getId().equals(pubgUser.getUserRole())) {
				sb.append(" UPDATE ");
				sb.append("   pubg_team ");
				sb.append(" SET ");
				sb.append("   INVITE_CODE = ? ");
				sb.append(" WHERE ");
				sb.append("   ROW_ID = ? AND CAPTAIN_ID LIKE '%" + pubgUser.getRowId() + ",%' ");
			} else if (UserConstant.USER_ROLE_30.getId().equals(pubgUser.getUserRole())) {
				sb.append(" UPDATE ");
				sb.append("   pubg_club ");
				sb.append(" SET ");
				sb.append("   INVITE_CODE = ? ");
				sb.append(" WHERE ");
				sb.append("   ROW_ID = ? AND MINISTER_ID LIKE '%" + pubgUser.getRowId() + ",%' ");
			}
			this.baseDao.safeUpdate(sb.toString(), 1, inviteCode, rowId);
		} catch (DataAccessException e) {
			throw new RuntimeException("更新邀请码出错！", e);
		}
	}

	/**
	 * 更新用户图片
	 * 
	 * @author 朱建文 创建时间：2018年4月10日 下午4:54:20
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
	public void updateUserPhoto(Long rowId, String photo) throws Exception {
		String sql = " UPDATE pubg_user SET PHOTO = ? WHERE ROW_ID = ? ";
		this.baseDao.safeUpdate(sql, 1, photo, rowId);
	}
	
	/**
	 * 获取队员详情
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 上午11:09:33
	 */
	public Map<String, Object> getMemberDetail(Integer userRole, Long rowId) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append("   ROW_ID rowId, USER_ACCOUNT userAccount, IFNULL(NICKNAME, '') nickname, IFNULL(PHOTO, '') photo, ");
		sql.append("   IFNULL(NICKNAME_INITIAL, '') nicknameInitial, IFNULL(LINK_QQ, '') linkQq, REAL_NAME_FLAG realNameFlag, ");
		sql.append("   IFNULL(GAME_ROLE, '') gameRole, IFNULL(USER_ROLE, '') userRole, IFNULL(BALANCE, 0) balance, ");
		sql.append("   IFNULL(MATCH_AMOUNT, 0) matchAmount, IFNULL(WIN_AMOUNT, 0) winAmount, IFNULL(WIN_SUM, 0) winSum ");
		sql.append(" FROM ");
		if (UserConstant.USER_ROLE_20.getId().equals(userRole)) {
			sql.append("   pubg_user ");
		} else if (UserConstant.USER_ROLE_30.getId().equals(userRole)) {
			sql.append("   pubg_user ");
		}
		sql.append(" WHERE ");
		sql.append("   ROW_ID = ? ");
		return baseDao.findMap(sql.toString(), rowId);
	}
	
	/**
	 * 更新用户的注册IP
	 * 
	 * @author 朱建文 创建时间：2018年5月7日 下午3:53:58
	 */
	@Transactional
	public void updaeRegIp(Long rowId, String regIp) {
		try {
			String sql = "UPDATE pubg_user SET REG_IP = ? WHERE ROW_ID = ? AND (REG_IP IS NULL OR LENGTH(REG_IP) > 15)";
			this.baseDao.safeUpdate(sql, 0, regIp, rowId);
		} catch (Exception e) {
			log.error("更新注册IP出错！" + rowId + "：" + regIp, e);
		}
	}
	
	/**
	 * 查询用户登陆的绑定信息
	 * 
	 * @author 朱建文 创建时间：2018年5月9日 上午10:21:46
	 */
	public List<PubgUserLoginBanding> findUserBandingInfo(Long userId, Integer thirdType) {
		try {
			String sql = "SELECT ROW_ID, USER_ID, USER_NAME, THIRD_ID, THIRD_NAME, THIRD_TYPE FROM pubg_user_login_banding";
			sql += " WHERE USER_ID = ? AND THIRD_TYPE = ?";
			return this.baseDao.findList(sql, RowMapperFactory.newInstance(PubgUserLoginBanding.class), userId, thirdType);
		} catch (DataAccessException e) {
			log.error("查询用户登陆的绑定信息出错！", e);
			return new ArrayList<PubgUserLoginBanding>();
		}
	}
}
